#include <assert.h>

#include "datamanager.h"

using namespace PBVP;

DataManager::DataManager()
{
	m_CurNodeId = -1;
}

DataManager::~DataManager()
{
	while(m_DataList.size() > 0) {
		DataNode *pDataNode = m_DataList.last();
		m_DataList.pop_back();
		delete pDataNode;
	}
}

void DataManager::clear()
{
	int n = m_DataList.size();
	while(m_DataList.size() > 0) {
		DataNode *pDataNode = m_DataList.last();
		m_DataList.pop_back();
		delete pDataNode;
	}
	if(n > 0) emit datasetChanged();
}

void DataManager::addDataNode(DataNode* pDatanode)
{
	m_DataList.push_back(pDatanode);
	m_BBox.merge(pDatanode->boundingBox());
	connect(pDatanode, SIGNAL(rendererChanged()), this, SLOT(changRenderer()));
	connect(pDatanode, SIGNAL(dataChanged()), this, SLOT(changeDataset()));
	emit datasetAdded();
	emit datasetChanged();
}

bool DataManager::deleteDataNode(int id)
{
	if (id >= m_DataList.size()) return false;
	DataNode* pDataNode = m_DataList[id];
	m_DataList.removeAt(id);
	delete pDataNode;
	updateBoundingBox();
	emit datasetDeleted();
	emit datasetChanged();
	return true;
}

bool DataManager::deleteDataNode(DataNode *pDataNode)
{
	for(int i = 0; i < m_DataList.size(); i++) 
	{
		DataNode *ptr = m_DataList[i];
		if(ptr == pDataNode) {
			m_DataList.removeAt(i);
			delete pDataNode;
			updateBoundingBox();
			emit datasetDeleted();
			emit datasetChanged();
			return true;
		}
	}
	// The DataNode pointer not found
	return false;
}

int DataManager::numOfDataSets() const
{
	return m_DataList.size();
}

void DataManager::render()
{
	for (int i = 0; i < m_DataList.size(); i++) {
		if(m_DataList[i]->isVisible()) {
			m_DataList[i]->render();
		}
	}
}

void DataManager::updateBoundingBox()
{
	m_BBox = AxisAlignedBox(-1, -1, -1, 1, 1, 1);
	for(int i = 0; i < m_DataList.size(); i++) {
		m_BBox.merge(m_DataList[i]->boundingBox());
	}
}

int DataManager::findDataNode(DataNode *pDataNode) const
{
	for(int i = 0; i < m_DataList.size(); i++)
	{
		DataNode *ptr = m_DataList[i];
		if(ptr == pDataNode) return i;
	} 
	return -1;
}

//////////////////////////////////////////////////////////////////////////
// slots
//////////////////////////////////////////////////////////////////////////
void DataManager::changRenderer()
{
	emit rendererChanged();
}

void DataManager::changeDataset()
{
	emit datasetChanged();
}

void DataManager::setCurrentNode(int id)
{
	m_CurNodeId = id;
}